package com.zfei.gfb.controller;

import cn.hutool.core.date.DateUtil;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.gson.JsonObject;
import com.zfei.gfb.api.StatsService;
import com.zfei.gfb.api.domain.StatsTag;
import com.zfei.gfb.api.domain.StatsValue;
import com.zfei.gfb.bean.Const;
import com.zfei.gfb.bean.Status;
import com.zfei.gfb.bean.StatusException;
import com.zfei.gfb.core.Auth;
import com.zfei.gfb.core.HttpJson;
import com.zfei.gfb.core.LogResult;
import com.zfei.gfb.dao.GfbJobWantedMapper;
import com.zfei.gfb.device.AppContext;
import com.zfei.gfb.model.GfbCompany;
import com.zfei.gfb.model.GfbJob;
import com.zfei.gfb.model.GfbJobWanted;
import com.zfei.gfb.model.GfbVillager;
import com.zfei.gfb.query.GfbJobWantedQuery;
import com.zfei.gfb.request.*;
import com.zfei.gfb.util.Beans;
import com.zfei.gfb.util.Gsons;
import com.zfei.gfb.util.Now;
import com.zfei.gfb.vo.GfbJobVo;
import com.zfei.gfb.vo.GfbJobWantedListVo;
import com.zfei.gfb.vo.GfbJobWantedVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.util.List;
import java.util.Map;

/**
 * @author
 * @version 1.0
 */
@Api(tags = "H5求职信息接口")
@RestController
@RequestMapping("/h5/job/want")
public class H5JobWantedController {

    @Resource
    private GfbJobWantedMapper gfbJobWantedMapper;

    @Resource
    private HttpSession httpSession;

    @Resource
    private StatsService statsService;


    @Auth(type = Const.VILLAGER)
    @ApiOperation(value = "我发布的求职信息")
    @ApiResponses({
            @ApiResponse(code = 200, message = "", response = GfbJobWantedVo.class),
    })
    @LogResult
    @HttpJson("/my/get")
    public Object getMy() {

        GfbVillager villager = (GfbVillager) httpSession.getAttribute(AppContext.SESSION_H5_VILLAGER);

        GfbJobWantedQuery query = new GfbJobWantedQuery();
        query.setUserId(villager.getId());
        List<GfbJobWanted> records = gfbJobWantedMapper.list(query);
        if (records.isEmpty()) {
            return null;
        }
        GfbJobWantedVo vo = Beans.copy(records.get(0), GfbJobWantedVo.class);
        return vo;
    }

    @Auth(type = Const.VILLAGER)
    @ApiOperation(value = "我的新增")
    @LogResult
    @HttpJson("/my/add")
    public Object addMy(@RequestBody H5JobWantedAddRequest request) {

        request.checkInsertNull();
        GfbVillager villager = (GfbVillager) httpSession.getAttribute(AppContext.SESSION_H5_VILLAGER);

        GfbJobWantedQuery query = new GfbJobWantedQuery();
        query.setUserId(villager.getId());
        List<GfbJobWanted> records = gfbJobWantedMapper.list(query);

        if (!records.isEmpty()) {
            throw new StatusException(Status.ENOUGH);
        }

        GfbJobWanted record = Beans.copy(request, GfbJobWanted.class);
        record.setUserId(villager.getId());
        record.setCreateTime(Now.millis());
        record.setUpdateTime(Now.millis());
        record.setCntime(DateUtil.now());

        Map<String, String> ext = Maps.newHashMap();
        ext.put("from", "client");
        ext.put("settleMethod", request.getSettleMethod());
        record.setExt(Gsons.toJson(ext));

        gfbJobWantedMapper.insertSelective(record);
        return null;
    }

    @Auth(type = Const.VILLAGER)
    @ApiOperation(value = "我的编辑")
    @LogResult
    @HttpJson("/my/edit")
    public Object editMy(@RequestBody GfbJobWantedEditRequest request) {
        request.checkUpdateNull();

        GfbJobWanted record = gfbJobWantedMapper.selectByPrimaryKey(request.getId());
        if (record == null) {
            throw new StatusException(Status.NOT_EXIST);
        }
        GfbVillager villager = (GfbVillager) httpSession.getAttribute(AppContext.SESSION_H5_VILLAGER);
        if (!record.getUserId().equals(villager.getId())) {
            throw new StatusException(Status.NOT_ALLOWED);
        }

        BeanUtils.copyProperties(request, record);
        record.setUpdateTime(Now.millis());

        Map<String, String> ext = Maps.newHashMap();
        ext.put("from", "client");
        ext.put("settleMethod", request.getSettleMethod());
        record.setExt(Gsons.toJson(ext));

        gfbJobWantedMapper.updateByPrimaryKeySelective(record);


        return null;
    }

    @Auth(type = Const.VILLAGER)
    @ApiOperation(value = "我的删除")
    @LogResult
    @HttpJson("/my/del")
    public Object delMy(@RequestBody GfbDelRequest request) {
        request.checkDelNull();

        GfbJobWanted record = gfbJobWantedMapper.selectByPrimaryKey(request.getId());
        if (record == null) {
            throw new StatusException(Status.NOT_EXIST);
        }
        GfbVillager villager = (GfbVillager) httpSession.getAttribute(AppContext.SESSION_H5_VILLAGER);
        if (!record.getUserId().equals(villager.getId())) {
            throw new StatusException(Status.NOT_ALLOWED);
        }
        gfbJobWantedMapper.deleteByPrimaryKey(request.getId());
        return null;
    }


    @ApiOperation(value = "求职信息2-3-3")
    @ApiResponses({
            @ApiResponse(code = 200, message = "", response = GfbJobWantedListVo.class),
    })
    @LogResult
    @HttpJson("/list")
    public Object list(@RequestBody GfbJobWantedQuery query) {
        query.build(Now::millis);

        GfbJobWantedListVo result = new GfbJobWantedListVo();

        int total = gfbJobWantedMapper.total(query);
        result.setTotal(total);
        if (total == 0) {
            result.setData(Lists.newArrayList());
            return result;
        }
        List<GfbJobWanted> records = gfbJobWantedMapper.list(query);
        List<GfbJobWantedVo> vos = Beans.copys(records, GfbJobWantedVo.class);
        vos.forEach(vo ->
        {
            String ext = vo.getExt();
            String from;
            if (StringUtils.isBlank(ext)) {
                from = "client";
            } else {
                JobExt jobExt = Gsons.fromJson(ext, JobExt.class);
                if (jobExt.getFrom() != null) {
                    from = jobExt.getFrom();
                    vo.setSettleMethod(jobExt.getSettleMethod());
                } else {
                    from = "client";
                }
            }
            vo.setFrom(from);
            vo.setBrowseNum(statsService.get(vo.getId().toString(), StatsTag.JOB_WANTED_BROWSE_COUNT).getNum());
        });
        result.setData(vos);

        return result;
    }

    public static class JobExt {
        private String from;
        private String settleMethod;

        public String getFrom() {
            return from;
        }

        public void setFrom(String from) {
            this.from = from;
        }

        public String getSettleMethod() {
            return settleMethod;
        }

        public void setSettleMethod(String settleMethod) {
            this.settleMethod = settleMethod;
        }
    }

    @ApiOperation(value = "求职详情")
    @ApiResponses({
            @ApiResponse(code = 200, message = "", response = GfbJobWantedVo.class),
    })
    @LogResult
    @HttpJson("/get")
    public Object get(@RequestBody GfbGetRequest request) {
        request.checkGetNull();
        Integer id = request.getId();

        GfbJobWanted record = gfbJobWantedMapper.selectByPrimaryKey(id);
        StatsValue postStats = new StatsValue(record.getId().toString(), StatsTag.JOB_WANTED_BROWSE_COUNT, 1);
        statsService.inc(postStats);
        GfbJobWantedVo vo = Beans.copy(record, GfbJobWantedVo.class);

        String ext = vo.getExt();
        String from;
        if (StringUtils.isBlank(ext)) {
            from = "client";
        } else {
            JobExt jobExt = Gsons.fromJson(ext, JobExt.class);
            if (jobExt.getFrom() != null) {
                from = jobExt.getFrom();
                vo.setSettleMethod(jobExt.getSettleMethod());
            } else {
                from = "client";
            }
        }
        vo.setFrom(from);
        vo.setBrowseNum(statsService.get(vo.getId().toString(), StatsTag.JOB_WANTED_BROWSE_COUNT).getNum());
        return vo;
    }
}
